import 'package:demo/common/routers/route_names.dart';
import 'package:demo/common/widgets/draggable_widget.dart';
import 'package:demo/config/env_config.dart';
import 'package:demo/pages/log/log_view.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:stack_trace/stack_trace.dart';
import 'package:talker_dio_logger/talker_dio_logger_settings.dart';
import 'package:talker_flutter/talker_flutter.dart';

import '../net/talker/talker_dio_logger_interceptor.dart';

class Log {
  static final talker = TalkerFlutter.init(
    settings: TalkerSettings(
      // 日志开关
      enabled: envConfig.isDebug,
    ),
  );

  /// 路由日志
  static final observer = TalkerRouteObserver(talker);

  /// dio日志
  static final dioLogger = TalkerDioLogger(
    talker: talker,
    settings: TalkerDioLoggerSettings(
      // Reposnse logs including http - headers 已修改日志实现
      printResponseHeaders: false,
      // All http responses enabled for console logging
      printResponseData: true,
      // 请求耗时
      printResponseTime: true,
      // All http requests disabled for console logging
      printRequestData: true,
      // Request logs without http - headersa
      printRequestHeaders: true,
      printErrorHeaders: false,
      //
      // responseFilter: (response) {
      //   // 翻译内容不打印
      //   return !response.requestOptions.path.contains("/translation/v1.json");
      // },
    ),
  );

  static OverlayEntry? _overlayEntry;

  // [Level.warning]
  static void w(dynamic message, {String? tag, Object? error, StackTrace? stackTrace}) {
    var frame = currentFrame;
    talker.warning("[${tag ?? frame.className}]$message", error, stackTrace ?? frame.stackTrace);
  }

  // [Level.deubg]
  static void d(dynamic message, {String? tag, Object? error, StackTrace? stackTrace}) {
    var frame = currentFrame;
    talker.debug("[${tag ?? frame.className}]$message", error, stackTrace ?? frame.stackTrace);
  }

  // [Level.info]
  static void i(dynamic message, {String? tag, Object? error, StackTrace? stackTrace}) {
    var frame = currentFrame;
    talker.info("[${tag ?? frame.className}]$message", error, stackTrace ?? frame.stackTrace);
  }

  // [Level.error]
  static void e(dynamic message, {String? tag, Object? error, StackTrace? stackTrace}) {
    var frame = currentFrame;
    talker.error("[${tag ?? frame.className}]$message", error, stackTrace ?? frame.stackTrace);
  }

  static void h(error, {dynamic msg, String? tag, StackTrace? stackTrace}) {
    var frame = currentFrame;
    talker.handle("[${tag ?? frame.className}]$error", stackTrace ?? frame.stackTrace, msg);
  }

  /// 获取调用处帧
  static ({StackTrace stackTrace, String className}) get currentFrame {
    if (!envConfig.isDebug) {
      // Release 模式下简化，避免性能开销
      return (stackTrace: StackTrace.empty, className: 'ReleaseMode');
    }

    StackTrace stackTrace = StackTrace.current;
    String className = "";
    try {
      // 解析 StackTrace 为 Trace 对象
      Trace trace = Trace.from(stackTrace);

      var frame = trace.frames.elementAtOrNull(2);
      if (frame != null) {
        stackTrace = Trace([frame]);

        // 假设 member 格式为 "ClassName.methodName" 或 "ClassName.methodName.<anonymous closure>"
        final parts = frame.member!.split('.');
        if (parts.isNotEmpty) {
          className = parts[0]; // 取第一个部分作为类名
        }
      }
    } catch (e) {
      return (stackTrace: StackTrace.empty, className: e.toString());
    }
    return (stackTrace: stackTrace, className: className);
  }

  static showDebugBtn(BuildContext context) {
    _overlayEntry = OverlayEntry(
      builder: (context) => DraggableWidget(
        onTap: () {
          toggleLogPage();
        },
        child: Container(
          padding: EdgeInsets.all(15),
          decoration: BoxDecoration(color: Colors.blue.withValues(alpha: 0.6), borderRadius: BorderRadius.circular(99)),
          child: Text("log", style: TextStyle(color: Colors.white)),
        ),
      ),
    );

    Overlay.of(context).insert(_overlayEntry!);
  }

  static hideDebugBtn() {
    _overlayEntry?.remove();
    _overlayEntry = null;
  }

  static toggleLogPage() {
    // 检查当前路由是否为目标页面
    if (Get.currentRoute == RouteNames.log) {
      // 如果目标页面已打开，关闭它
      Get.back();
    } else {
      // 如果目标页面未打开，打开它
      LogPage.open();
    }
  }
}
